Defining an Interface

 

Interface can be used to specify what a class must do, but not how it does it. Interfaces are similar to classes, but they lack instance variables, and their methods are declared without any body. Once it is defined, any number of classes can implement an interface. Also, one class can implement any number of interfaces. By providing the interface keyword, Java allows you to fully utilize the “one interface, multiple methods” aspect of polymorphism. Interfaces are designed to support dynamic method resolution at run time.

2.1 Defining an Interface :

An interface is defined much like a class. This is the general form of an interface:

access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
return-type method-nameN(parameter-list);
type final-varnameN = value;
}

When it is declared as public, the interface can be used by any other code. The methods that are declared have no bodies. They end with a semicolon after the parameter list. They are abstract methods; there can be no default implementation of any method specified within an interface. Each class that includes an interface must implement all of the methods.

Variables can be declared inside of interface declarations. They are implicitly final and static. All methods and variables are implicitly public.

 

 

JAVA Packages and Interfaces